import { Space, TableColumnType } from 'antd'
import React, { useState } from 'react'
import { TableWidthConf } from '@/conf'

interface OperationRecord {
  record: any
  index: number
}

interface OperationColumnProps extends TableColumnType {
  /** 按钮组 */
  buttons?: React.ReactNode[]
}

export interface OperationColumnState {
  /**
   * 内部按通用配置封装的操作列
   */
  operationColumn: TableColumnType
  /**
   * 当前选择的操作列的记录
   */
  operationRecord?: any
  /**
   * 当前选择的操作列的索引
   */
  operationIndex?: number
}

/**
 * 构建操作列，并Hook当前操作行及下标
 */
export const useOperationColumn = (
  props: OperationColumnProps,
): OperationColumnState => {
  const [value, setValue] = useState<OperationRecord>()

  const { buttons, ...restProps } = props

  const operationColumn = {
    title: '操作',
    dataIndex: 'opeartion',
    width: TableWidthConf.operation,
    fixed: 'right',
    ...restProps,
    render: (_, record, index) => {
      return (
        <Space
          onClick={() => {
            setValue({ record, index })
          }}
        >
          {buttons}
        </Space>
      )
    },
  } as TableColumnType

  return {
    operationColumn,
    operationRecord: value?.record,
    operationIndex: value?.index,
  }
}
